package structure

import "gddgame.cc/galaxy/utils"

type RelationStruct struct {
}

// Relation: 多对多，有顺序
func (execute *Execute) GetRelation(conn SafeConn, data Data, relation string) []BaseData {
	//lrange 0,-1
	c, _ := conn.Do("LRANGE", execute.Key+"/"+execute.GetDataType(data.GetDataType())+utils.ToString(data.GetId())+"/"+relation, 0, -1)
	if c == nil {
		return nil
	}
	rl := make([]BaseData, len(c.([]interface{})))
	for index, v := range c.([]interface{}) {
		r := BaseData{}
		_, _ = r.UnmarshalMsg(v.([]byte))
		rl[index] = r
	}
	return rl
}

func (execute *Execute) AddRelation(conn SafeConn, data1 Data, data2 Data, relation string) {
	key := execute.Key + "/" + execute.GetDataType(data1.GetDataType()) + utils.ToString(data1.GetId())
	//conn.Watch(key)
	_ = conn.Send("RPUSH", key+"/"+relation, data2.Bytes())
	_ = conn.Send("HSET", key, "relation/"+relation, 1)

	key = execute.Key + "/" + execute.GetDataType(data2.GetDataType()) + utils.ToString(data2.GetId())
	//conn.Watch(key)
	_ = conn.Send("RPUSH", key+"/"+relation, data1.Bytes())
	_ = conn.Send("HSET", key, "relation/"+relation, 1)
}

func (execute *Execute) RemoveRelation(conn SafeConn, data1 Data, data2 Data, relation string) {
	key := execute.Key + "/" + execute.GetDataType(data1.GetDataType()) + utils.ToString(data1.GetId()) + "/" + relation
	_, _ = conn.Do("LREM", key, 0, data2.Bytes())

	key = execute.Key + "/" + execute.GetDataType(data2.GetDataType()) + utils.ToString(data2.GetId()) + "/" + relation
	_, _ = conn.Do("LREM", key, 0, data1.Bytes())
}

func (execute *Execute) ClearRelation(conn SafeConn, data Data, relation string) {
	rl := execute.GetRelation(conn, data, relation)
	if rl == nil || len(rl) == 0 {
		return
	}

	for _, v := range rl {
		key := execute.Key + "/" + execute.GetDataType(v.DataType) + utils.ToString(v.Id) + "/" + relation
		_, _ = conn.Do("LREM", key, 0, data.Bytes())
	}
	_ = conn.Send("DEL", execute.Key+"/"+execute.GetDataType(data.GetDataType())+utils.ToString(data.GetId())+"/"+relation)
	_ = conn.Send("HSET", execute.Key+"/"+execute.GetDataType(data.GetDataType())+utils.ToString(data.GetId()), "relation/"+relation, 0)
}
